package com.viewdraghelper;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

public class NSLayout extends LinearLayout {

    private static final String TAG = "NSLayout";

    class DragCallBack extends ViewDragHelper.Callback {

        @Override
        public boolean tryCaptureView(@NonNull View child, int pointerId) {
            return true;
        }

        @Override
        public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
            return Math.min(Math.max(0, left), getWidth() - child.getWidth());
        }

        @Override
        public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
            return Math.min(Math.max(0, top), getHeight() - child.getHeight());
        }

        @Override
        public int getViewHorizontalDragRange(View child) {
            return 1;
        }

        @Override
        public int getViewVerticalDragRange(View child) {
            return 1;
        }
    }

    private ViewDragHelper dragHelper;

    public NSLayout(Context context) {
        super(context);
    }

    public NSLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        dragHelper = ViewDragHelper.create(this, new DragCallBack());
    }

    private MotionEvent downEv;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            downEv = MotionEvent.obtain(ev);
        } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            if (downEv != null) {
                //欺骗VDH 模拟完整的down->move->up 事件流
                onTouchEvent(downEv);
                downEv = null;
            }
        }
        return dragHelper.shouldInterceptTouchEvent(ev);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        dragHelper.processTouchEvent(event);
        return true;
    }
}
